<template>
  <div class="image-selector">
    <el-button @click="showDialog = true" :icon="Picture">
      {{ selectedImagePath ? '更换图片' : '选择图片' }}
    </el-button>
    
    <!-- 当前选择的图片预览 -->
    <div v-if="selectedImagePath" class="current-image">
      <img :src="`http://localhost:8080/${selectedImagePath}`" alt="当前选择的图片" />
      <div class="image-path">{{ selectedImagePath }}</div>
      <el-button size="small" type="danger" @click="clearSelection" :icon="Delete">清除</el-button>
    </div>

    <!-- 图片选择对话框 -->
    <el-dialog v-model="showDialog" title="选择图片" width="80%" top="5vh">
      <div class="image-selector-dialog">
        <!-- 分类选择 -->
        <div class="category-selector">
          <el-radio-group v-model="selectedCategory" @change="loadCategoryImages">
            <el-radio-button label="all">全部图片</el-radio-button>
            <el-radio-button v-for="category in categories" :key="category" :label="category">
              {{ getCategoryDisplayName(category) }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 图片网格 -->
        <div class="images-grid">
          <div v-if="selectedCategory === 'all'">
            <div v-for="(images, category) in allImages" :key="category" class="category-section">
              <h4 class="category-title">{{ getCategoryDisplayName(category) }}</h4>
              <div class="image-grid">
                <div 
                  v-for="image in images" 
                  :key="image.path" 
                  class="image-item"
                  :class="{ selected: tempSelectedPath === image.path }"
                  @click="selectImage(image)"
                >
                  <img :src="`http://localhost:8080/${image.path}`" :alt="image.name" />
                  <div class="image-name">{{ image.name }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="image-grid">
            <div 
              v-for="image in categoryImages[selectedCategory] || []" 
              :key="image.path" 
              class="image-item"
              :class="{ selected: tempSelectedPath === image.path }"
              @click="selectImage(image)"
            >
              <img :src="`http://localhost:8080/${image.path}`" :alt="image.name" />
              <div class="image-name">{{ image.name }}</div>
            </div>
          </div>
        </div>

        <!-- 选择信息 -->
        <div v-if="tempSelectedImage" class="selected-info">
          <h4>当前选择：</h4>
          <div class="selected-details">
            <img :src="`http://localhost:8080/${tempSelectedImage.path}`" :alt="tempSelectedImage.name" />
            <div class="selected-meta">
              <p><strong>文件名：</strong>{{ tempSelectedImage.name }}</p>
              <p><strong>路径：</strong>{{ tempSelectedImage.path }}</p>
              <p><strong>大小：</strong>{{ formatFileSize(tempSelectedImage.size) }}</p>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!tempSelectedImage">确认选择</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Delete } from '@element-plus/icons-vue'

interface ImageInfo {
  name: string
  path: string
  category?: string
  size: number
  lastModified: number
}

interface Props {
  modelValue?: string
  placeholder?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '选择图片'
})

const emit = defineEmits<Emits>()

const showDialog = ref(false)
const categories = ref<string[]>([])
const categoryImages = ref<Record<string, ImageInfo[]>>({})
const allImages = ref<Record<string, ImageInfo[]>>({})
const selectedCategory = ref('all')
const tempSelectedImage = ref<ImageInfo | null>(null)
const tempSelectedPath = ref('')

// 当前选择的图片路径
const selectedImagePath = ref(props.modelValue)

// 监听外部传入的值变化
watch(() => props.modelValue, (newValue) => {
  selectedImagePath.value = newValue
})

// 分类显示名称映射
const categoryDisplayNames: Record<string, string> = {
  attractions: '景点图片',
  food: '美食图片',
  culture: '文化图片',
  carousel: '轮播图片'
}

const getCategoryDisplayName = (category: string) => {
  return categoryDisplayNames[category] || category
}

// 加载图片分类
const loadCategories = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/images/categories')
    if (response.ok) {
      categories.value = await response.json()
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载所有图片
const loadAllImages = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/images/all')
    if (response.ok) {
      allImages.value = await response.json()
    }
  } catch (error) {
    console.error('加载图片失败:', error)
  }
}

// 加载指定分类的图片
const loadCategoryImages = async (category?: string) => {
  const targetCategory = category || selectedCategory.value
  if (targetCategory === 'all') {
    await loadAllImages()
    return
  }
  
  try {
    const response = await fetch(`http://localhost:8080/api/images/category/${targetCategory}`)
    if (response.ok) {
      const images = await response.json()
      categoryImages.value[targetCategory] = images
    }
  } catch (error) {
    console.error(`加载分类 ${targetCategory} 图片失败:`, error)
  }
}

// 选择图片
const selectImage = (image: ImageInfo) => {
  tempSelectedImage.value = image
  tempSelectedPath.value = image.path
}

// 确认选择
const confirmSelection = () => {
  if (tempSelectedImage.value) {
    selectedImagePath.value = tempSelectedImage.value.path
    emit('update:modelValue', tempSelectedImage.value.path)
    emit('change', tempSelectedImage.value.path)
    showDialog.value = false
    ElMessage.success('图片选择成功')
  }
}

// 清除选择
const clearSelection = () => {
  selectedImagePath.value = ''
  emit('update:modelValue', '')
  emit('change', '')
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 初始化数据
const initData = async () => {
  await loadCategories()
  await loadAllImages()
}

// 监听对话框打开，重置临时选择
watch(showDialog, (newValue) => {
  if (newValue) {
    tempSelectedImage.value = null
    tempSelectedPath.value = ''
    // 如果当前有选择的图片，在对话框中高亮显示
    if (selectedImagePath.value) {
      tempSelectedPath.value = selectedImagePath.value
    }
  }
})

onMounted(() => {
  initData()
})
</script>

<style scoped>
.image-selector {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.current-image {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f9f9f9;
}

.current-image img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.image-path {
  flex-grow: 1;
  font-size: 14px;
  color: #666;
}

.image-selector-dialog {
  max-height: 60vh;
  overflow-y: auto;
}

.category-selector {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.category-section {
  margin-bottom: 20px;
}

.category-title {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}

.image-item {
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.image-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.image-item.selected {
  border-color: #e74c3c;
  box-shadow: 0 2px 8px rgba(231, 76, 60, 0.3);
}

.image-item img {
  width: 100%;
  height: 80px;
  object-fit: cover;
  display: block;
}

.image-name {
  padding: 5px;
  font-size: 12px;
  text-align: center;
  background: white;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selected-info {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f9f9f9;
}

.selected-info h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.selected-details {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-details img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.selected-meta p {
  margin: 3px 0;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 